package io.zerous.gravitation

import android.graphics.Color
import io.zerous.engine.Zex
import io.zerous.engine.utils.ZCamera

/**
 * Created by Zerous on 2018/9/23.
 */
class PhysicsWorld(val ZCamera: ZCamera) {
    val particles = ArrayList<Particle>()

    val colors = intArrayOf(Color.RED, Color.GREEN, Color.BLUE)

    val G = 0.00006f

    fun addParticle(particle: Particle) {
        particles.add(particle)
    }

    fun pUpdate() {
        for ((i, sp) in particles.withIndex()) {
            for ((j, p) in particles.withIndex()) {
                if (i == j) {
                    continue
                }
                val d = sp.position - p.position
                //p.acceleration += d * (G * sp.mass / d.squaredLen() * d.len())
                p.addForce(d * (G * (sp.mass * p.mass / d.squaredLen() * d.len())))
            }
        }
    }

    fun update() {
        for (particle in particles) {
            particle.velocity += particle.acceleration

            // TODO("碰撞处理")
            for (sp in particles) {
                if (sp == particle) continue
                val distance = sp.position - particle.position
                if (distance.squaredLen() <= 3600f) {
                    sp.velocity.set(sp.velocity)
                }
            }

            particle.position += particle.velocity

            particle.acceleration.set(0f, 0f)
        }
    }

    fun draw() {
        for ((i, particle) in particles.withIndex()) {
            Zex.graphics.drawCircle(Zex.graphics.width/2f - ZCamera.position.x + particle.position.x, Zex.graphics.height/2f - ZCamera.position.y + particle.position.y, if (particle.mass > 1000) 30f else 10f, color = if (i < 3) colors[i] else 0)
        }
    }
}